from conn_manager import BASE_DATA_DIR, EMAIL_CONFIG
import os
import json
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import traceback

class FAQFileChecker:
    def __init__(self, file_path=BASE_DATA_DIR):
        # 修复路径：BASE_DATA_DIR 已经包含了完整路径
        faq_recorder = os.path.join(file_path, 'faq-recorder.json')
        
        # 如果记录文件不存在，创建默认记录
        if not os.path.exists(faq_recorder):
            print(f"📄 首次运行，创建文件记录: {faq_recorder}")
            os.makedirs(os.path.dirname(faq_recorder), exist_ok=True)
            default_data = {
                'last_update_time': '1970-01-01 00:00:00',
                'file_structure': {'faq': [], 'errorcode': []}
            }
            with open(faq_recorder, 'w', encoding='utf-8') as f:
                json.dump(default_data, f, ensure_ascii=False, indent=2)
            self.faq_recorder_data = default_data
        else:
            self.faq_recorder_data = json.load(open(faq_recorder, 'r', encoding='utf-8'))
            
        self.last_update_time = self.faq_recorder_data['last_update_time']
        self.file_structure = self.faq_recorder_data['file_structure']
    def get_current_file_structure(self):
        """
        1. 遍历BASE_DATA_DIR/data目录下 faq和 errorcode目录下的所有文件
        2. 根据文件名和文件路径，以及文件大小，将文件信息添加到file_structure中
        3. 返回当前的file_structure
        """
        current_structure = {'faq': [], 'errorcode': []}
        
        # data_dir = os.path.join(BASE_DATA_DIR, 'data')
        print(f"🔍 正在扫描数据目录: {BASE_DATA_DIR}")
        
        for category in ['faq', 'errorcode']:
            category_dir = os.path.join(BASE_DATA_DIR, category)
            print(f"📂 检查类别目录: {category_dir}")
            
            if os.path.exists(category_dir):
                print(f"✅ 目录存在: {category_dir}")
                all_files = []
                txt_files = []
                
                for root, dirs, files in os.walk(category_dir):
                    print(f"📁 扫描子目录: {root}")
                    print(f"📄 找到文件: {files}")
                    all_files.extend(files)
                    
                    for file in files:
                        if file.endswith('.txt'):  # 只处理txt文件
                            file_path = os.path.join(root, file)
                            file_size = os.path.getsize(file_path)
                            current_structure[category].append({
                                'file_name': file,
                                'file_path': file_path,
                                'file_size': file_size
                            })
                            txt_files.append(file)
                            print(f"📝 添加txt文件: {file} ({file_size} bytes)")
                
                print(f"📊 {category} 统计: 总文件{len(all_files)}个, txt文件{len(txt_files)}个")
                if all_files and not txt_files:
                    print(f"⚠️ 注意: {category}目录有文件但没有.txt文件")
                    print(f"   文件列表: {all_files}")
            else:
                print(f"❌ 目录不存在: {category_dir}")
        
        return current_structure

    def compare_file_structure(self, new_file_structure):
        """
        对比输入的new_file_structure和self.file_structure，
        将区别信息返回：
        {
            'new_file': [
                {'file_name': '', 'file_path': '', 'file_size': 0},
            ],
            'deleted_file': [
                {'file_name': '', 'file_path': '', 'file_size': 0},
            ],
            'updated_file': [
                {'file_name': '', 'file_path': '', 'file_size': 0},
            ]
        }
        """
        result = {'new_file': [], 'deleted_file': [], 'updated_file': []}
        
        for category in ['faq', 'errorcode']:
            # 创建旧文件字典，以file_name为key
            old_files = {file['file_name']: file for file in self.file_structure.get(category, [])}
            new_files = {file['file_name']: file for file in new_file_structure.get(category, [])}
            
            # 找出新增文件
            for file_name, file_info in new_files.items():
                if file_name not in old_files:
                    result['new_file'].append(file_info)
                else:
                    # 比较文件大小，如果不同则认为文件已更新
                    old_size = old_files[file_name]['file_size']
                    new_size = file_info['file_size']
                    if old_size != new_size:
                        result['updated_file'].append(file_info)
            
            # 找出删除的文件
            for file_name, file_info in old_files.items():
                if file_name not in new_files:
                    result['deleted_file'].append(file_info)
        
        return result
    
    def update_file_structure_record(self, new_structure):
        """更新文件结构记录到json文件"""
        import datetime
        
        updated_data = {
            'last_update_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'file_structure': new_structure
        }
        
        # 修复路径：BASE_DATA_DIR 已经包含了完整路径
        faq_recorder_path = os.path.join(BASE_DATA_DIR, 'faq-recorder.json')
        os.makedirs(os.path.dirname(faq_recorder_path), exist_ok=True)
        
        with open(faq_recorder_path, 'w', encoding='utf-8') as f:
            json.dump(updated_data, f, ensure_ascii=False, indent=2)
        
        print(f"📝 文件结构记录已更新: {faq_recorder_path}")

def check_file_changes():
    """检测文件更改的主函数"""
    try:
        # 初始化检查器
        checker = FAQFileChecker()
        
        # 获取当前文件结构
        current_structure = checker.get_current_file_structure()
        
        # 对比文件结构
        changes = checker.compare_file_structure(current_structure)
        
        # 统计变更
        new_count = len(changes['new_file'])
        updated_count = len(changes['updated_file'])  
        deleted_count = len(changes['deleted_file'])
        
        print(f"📊 文件变更统计: 新增{new_count}个, 更新{updated_count}个, 删除{deleted_count}个")
        
        # 判断是否有变更
        has_changes = new_count > 0 or updated_count > 0 or deleted_count > 0
        
        if has_changes:
            # 准备邮件内容
            email_content = f"""
📊 本次检测到的文件变更:
• ✨ 新增文件: {new_count} 个
• 🔄 更新文件: {updated_count} 个  
• 🗑️ 删除文件: {deleted_count} 个

详细变更信息:
"""
            
            for change_type, files in changes.items():
                if files:
                    change_type_zh = {'new_file': '新增', 'updated_file': '更新', 'deleted_file': '删除'}
                    email_content += f"\n{change_type_zh[change_type]}文件:\n"
                    for file_info in files:
                        email_content += f"  📄 {file_info['file_name']} ({file_info['file_size']} bytes)\n"
            
            # 发送邮件通知
            send_email(email_content)
            
            # 更新文件记录
            checker.update_file_structure_record(current_structure)
            
            print("✅ 检测到文件变更，已发送通知邮件并更新记录")
        else:
            print("😌 没有检测到文件变更")
            
        # 返回变更信息，供后续任务使用
        return {
            'has_changes': has_changes,  
            'changes': changes,
            'files_to_upload': changes['new_file'] + changes['updated_file']  # 需要上传的文件
        }
        
    except Exception as e:
        print(f"❌ 文件检测过程中出错: {str(e)}")
        print(f"🔍 详细错误信息:\n{traceback.format_exc()}")
        return {
            'has_changes': False,
            'changes': {'new_file': [], 'updated_file': [], 'deleted_file': []},
            'files_to_upload': []
        }

def send_email(text: str='Nothing'):
    """Send email with the address book attachment."""
    try:
        msg = MIMEMultipart()
        msg['From'] = EMAIL_CONFIG['sender']
        msg['To'] = ', '.join(EMAIL_CONFIG['receivers'])
        msg['Subject'] = '【AGI】爬虫产品链接更新通知'

        # Add email body
        body = f"""哈喽，本爬虫检测到FAQ,ERRORCODE有改动！  
        详情请查看：http://192.168.40.16:8080/dags/unified_crawler  
        ------------------------------------
        {text}

        ------------------------------------
        技术中心-AGI应用部 の 可爱小爬虫 😉
        bluetti-agi@poweroak.net
        """
        msg.attach(MIMEText(body, 'plain'))

        # Send email
        with smtplib.SMTP_SSL(EMAIL_CONFIG['smtp_server'], EMAIL_CONFIG['smtp_port']) as server:
            server.login(EMAIL_CONFIG['username'], EMAIL_CONFIG['password'])
            server.send_message(msg)

        print(f"✅ Email sent successfully with content: {body}")
        return True
    except Exception as e:
        print(f"❌ Error sending email: {e} - {traceback.format_exc()}")
        return False
    
if __name__ == "__main__":
    print("🚀 开始测试文件检测功能...")
    result = check_file_changes()
    print("📊 检测结果:")
    print(f"  有变更: {result['has_changes']}")
    print(f"  需要上传的文件数量: {len(result['files_to_upload'])}")
    for file_info in result['files_to_upload']:
        print(f"    📄 {file_info['file_name']} ({file_info['file_size']} bytes)")